<h1>Keyboard Map</h1>

<pre class="metadata">
Shortname: keyboard-map
Level:
Group: WICG
Status: CG-DRAFT
ED: https://wicg.github.io/keyboard-map/
Repository: wicg/keyboard-map
!Explainer: <a href="https://github.com/wicg/keyboard-map/blob/master/explainer.md">Keyboard Map Explainer</a>
Editor:
    Gary Kacmarcik, Google, garykac@google.com
Abstract:
	This specification defines an API that allows websites to convert from a given
	{{KeyboardEvent/code}} value to a
	valid {{KeyboardEvent/key}} value that can be shown to the user to
	identify the given key.
	The conversion from {{KeyboardEvent/code}} to {{KeyboardEvent/key}} is based on
	the user's currently selected keyboard layout.
	It is intended to be used by web applications that want to treat the keyboard as a
	set of buttons and need to describe those buttons to the user.

Status Text:
	This document is an editor's draft proposed as a First Public Working Draft.
	
</pre>

<pre class="anchors">
urlPrefix: http://www.w3.org/TR/uievents/#; type: dfn; spec: uievents;
	text: dead key
urlPrefix: http://www.w3.org/TR/uievents-key/#; type: dfn; spec: uievents-key;
	text: key attribute value
urlPrefix: http://www.w3.org/TR/uievents-code/#; type: dfn; spec: uievents-code;
	text: writing system keys
urlPrefix: http://www.w3.org/TR/uievents-code/#code-; type: dfn; spec: uievents-code;
	text: Quote
</pre>

<h2 id="introduction">Introduction</h2>

	On a {{KeyboardEvent}}, the {{KeyboardEvent/code}} attribute encodes
	a value that represents the physical location of the key that was pressed. This value
	ignores the current locale (e.g., "en-US"), layout (e.g., "dvorak") and modifier state
	(e.g., "Shift + Control"), so it is ideally suited for applications (like games) that
	want to use the keyboard as a set of generic buttons. The idea behind the
	{{KeyboardEvent/code}} attribute is that it provides a platform-neutral
	[=scancode=] for each physical key.

	The {{KeyboardEvent/key}} attribute, on the other hand, contains the value that is
	generated by the key press, accounting for the locale, layout, and modifier
	keys. Almost every Unicode character is a valid `key` attribute, along with a number
	of special named values (see {{KeyboardEvent}} [=key attribute values=]),
	so there are thousands of possible {{KeyboardEvent/key}} values.

	Because most users have a physical keyboard that matches their locale and layout,
	we can reasonably assume that the {{KeyboardEvent/key}} value is a good stand-in for
	the glyph printed on the keycap. While this does not hold true when the user has
	selected a different layout, in that case the user is well-aware of the mismatch
	between the glyph on the keycap and the character generated by a key press.
	
	The API described in this document provides a simple way of obtaining this basic
	{{KeyboardEvent/code}} to {{KeyboardEvent/key}} mapping.


<h2 id="API">Keyboard Map API</h2>

	<h3 id="navigator-interface">Navigator Interface</h3>

		<pre class="idl" data-highlight="webidl">
		[Exposed=Window]
		partial interface Navigator {
			[SecureContext, SameObject] readonly attribute Keyboard keyboard;
		};
		</pre>

		<div id="navigator-idl" dfn-for="Navigator">

		<div class="algorithm" data-algorithm="navigator-keyboard">
		<h4 id="h-navigator-keyboard"><dfn>keyboard</dfn></h4>
		The [=keyboard=] attribute must return the {{Navigator}}'s {{Keyboard}} object.
		</div>

		</div><!-- dfn-for Navigator -->

		Note: The [=keyboard=] object is also defined in the 
		<a href="https://w3c.github.io/keyboard-lock/#navigator-interface">Keyboard Lock</a>
		specification. These two definitions will be reconciled once we decide on a final
		home for these specifications.
		
	<h3 id="keyboardlayoutmap-interface">KeyboardLayoutMap Interface</h3>

		<pre class="idl" data-highlight="webidl">
		[Exposed=Window]
		interface KeyboardLayoutMap {
			readonly maplike&lt;DOMString, DOMString>;
		};
		</pre>
		
		<div id="keyboardlayoutmap-idl" dfn-for="KeyboardLayoutMap">

		The {{KeyboardLayoutMap}} is a readonly collection of mappings from
		{{KeyboardEvent/code}} values to {{KeyboardEvent/key}} values.

		</div><!-- dfn-for KeyboardLayoutMap -->
		
	<h3 id="keyboard-interface">Keyboard Interface</h3>

		<pre class="idl" data-highlight="webidl">
		[SecureContext, Exposed=Window] interface Keyboard {
			Promise&lt;KeyboardLayoutMap> getLayoutMap();
		};
		</pre>

		<div id="keyboard-idl" dfn-for="Keyboard">

		<div class="algorithm" data-algorithm="keyboard-getlayoutmap">
		<h4 id="h-keyboard-getlayoutmap"><dfn>getLayoutMap()</dfn></h4>

			When [=getLayoutMap()=] is called, the user agent must
			run the following steps:

			1. Let |p| be a new {{Promise}}.
			
			1. If not currently executing in the currently active [=top-level browsing context=], then
		
				1. Reject |p| with an "{{InvalidStateError}}" {{DOMException}}.

			1. Run the following steps [=in parallel=]:
			
				1. Let |map| be a new {{KeyboardLayoutMap}} that is initially empty.
		
				1. For each value |code| in the "KeyboardEvent code" column of the
					[=Writing System Keys=] table

					1. Let |layout| be the highest priority [=ASCII-capable=] keyboard layout,
						or the highest priority keyboard layout if none of the available
						layouts are [=ASCII-capable=].

					1. If |code| is not a valid key in the |layout|, then continue
				
					1. Let |key| be the {{KeyboardEvent/key}} value that would be generated
						by |layout|
						if the key identified by |code| was pressed with no modifiers.

					1. If |key| is a [=dead key=], then
				
						1. Set |key| to the standalone character that corresponds
							to the [=dead key=], as defined in the
							<a href="#table1">Standalone Equivalents for Dead Keys</a> table.
						
					1. Create a map entry |e| from the pair < |code|, |key| >
				
					1. Add |e| to |map|.
			
				1. Resolve |p| with |map|.
			
			1. Return |p|.

			<div></div>
			
			User agents may choose to cache the |map| and return the cached value as
			long as the cache is updated (or invalidated) whenever the keyboard layout
			changes.
			
			<div class="example">
			To show instructions about which key to press in a game:
			<pre>
				navigator.keyboard.getLayoutMap().then(function(map) {
					var keyUp = map.get("KeyW");
					showUserDialog("Press " + keyUp + " to move up.");
				});
			</pre>
			</div>

			<div class="example">
			On a "US International" keyboard where the single-quote (') key is a
			[=dead key=] that adds an acute accent to the following character.
			The keyboard map would contain an entry mapping [=Quote=] (the 
			{{KeyboardEvent/code}} for this key) to "'" (the single-quote character U+0027).
			</div>

		</div><!-- getLayoutMap() -->

		</div><!-- dfn-for Keyboard -->

	<h3 id="dead-and-combining">Dead Keys and Combining Characters</h3>

		Since the intent of the keyboard map API is to provide human-readable
		descriptions for keys on the user's keyboard, [=dead keys=] or
		combining characters need to be converted into standalone forms so that
		they can be used directly.
		
		The following table defines how to map from common [=dead keys=] and
		combining characters into standalone characters.
		
		<table>
		<caption id="table1">Table 1: Standalone Equivalents for Dead Keys</caption>
		<thead><tr><th>Dead Key<br/>Name</th><th>Unicode<br/>Combining</th><th>Standalone<br/>Character</th><th>Unicode<br/>Standalone</th></tr></thead>
		<tbody>
		<tr><td>Grave</td><td>U+0300</td><td>"`"</td><td>U+0060</td></tr>
		<tr><td>Acute</td><td>U+0301</td><td>"'"</td><td>U+0027</td></tr>
		<tr><td>Circumflex</td><td>U+0302</td><td>"^"</td><td>U+005e</td></tr>
		<tr><td>Tilde</td><td>U+0303</td><td>"~"</td><td>U+007e</td></tr>
		<tr><td>Diaeresis</td><td>U+0308</td><td>"¨"</td><td>U+00a8</td></tr>
		</tbody>
		</table>
		
	<h3 id="ascii-capable-layouts">ASCII-Capable Keyboard Layouts</h3>

		
		An <dfn>ASCII-capable</dfn> keyboard layout is one that:
		
		* Is capable of producing all of the basic ASCII characters "A" - "Z" without
			requiring the use of any modifier keys.

		* Produces a valid, printable character for all the [=common writing system keys=].

		The <dfn>common writing system keys</dfn> are those that are common to all
		keyboard layouts, as shown in blue in
		<a href="https://www.w3.org/TR/uievents-code/#figure-keyboard-codes-alphanum1">Figure 13</a>
		of the [[UIEvents-Code]] specification.

<h2 id="keyboard-events">Keyboard Events</h2>

	<h3 id="layoutchange-event">The <dfn>layoutchange</dfn> Event</h2>
	
		The [=layoutchange=] event fires on the [=keyboard=] object whenever the
		current keyboard layout is changed. A layout change can occur when the user
		selects a new layout, or it may happen automatically when the user performs an
		action (e.g., switching to an application that has a preferred layout).
		
		Note the following:
		
		* Modifying the set of available layouts does not trigger a [=layoutchange=]
			event, unless the modification changes the current layout.
		
		* Adding or removing a physical keyboard does not trigger an event unless
			the system has functionality to change the current layout based on adding or 
			removing a physical keyboard. But note that it is the layout change that
			triggers this event, not the act of adding or removing the physical keyboard.
		
		* The event will be fired whenever the current layout changes, even if the
			highest priority ASCII-capable layout remains the same.

		If the keyboard layout changes while the user agent is not the foreground
		application, then the [=layoutchange=] event MUST fire when the user agent
		regains focus.

		<div class="example">
		To handle this event:
		<pre>
			navigator.keyboard.addEventListener("layoutchange", function() {
				// Update user keyboard map settings
				updateGameControlSettingsPage();
			});
		</pre>
		</div>
	
<h2 id="mobile">Mobile Device Considerations</h2>

	Since this is a keyboard-focused API and mobile devices do not commonly
	have physical keyboards, this API will not typically be present or
	supported on mobile devices.
	
	However, mobile devices may choose to support this API if they allow physical
	keyboards to be connected. In this case, they may return a subset of the
	[=Writing System Keys=] that are appropriate for the platform.
	
	Mobile platforms that require the user to configure their physical keyboard
	layout (and don't provide a reasonable default), may support this API by returning a
	layout map that contains no entries.

<h2 id="security">Security Considerations</h2>

	This API returns static data and does not change any system state, so there are
	no special security concerns.
	
<h2 id="privacy">Privacy Considerations</h2>

	As with all APIs that return information about the current device state, there is
	a risk of using this API to create a larger "fingerprint" of the user than if this
	API was not available.
	
	By returning info from the highest priority ASCII-capable keyboard layout instead of
	the active layout, the value of this information for fingerprinting is reduced since
	users are more likely to share the same values.
	
	Note the following situations where this layout information might be used to identify
	individuals:
	
	* Users who use uncommon ASCII layouts (like Dvorak or Colemak)
	
	* Users who use an ASCII layout that doesn't match the default for the region that
		they are in. For example, a user in the US with an active UK or French layout.
	
	Without this API, similar fingerprinting can still be attempted, but it is more
	difficult since it would require the user to interact with the page by typing
	characters and analyze the resulting {{KeyboardEvent}}s.
	
	<h3 id="privacy-mitigations">Privacy Mitigations</h3>
	
	As a first line of defense for the user, this specification requires that the API
	is only available from [=secure contexts=] and can only be called from the currently
	active [=top-level browsing context=].

	User agents that are concerned about the privacy impact of providing this
	keyboard mapping information can also consider the following mitigations:
	
	* Having a user prompt to ask for permission whenever a site attempts to use this API.
	
	* Always return a "standard" mapping. Although note that the standard mapping
		would need to vary for different parts of the world. For example, a user agent that
		had a "privacy mode" that always returned a US-QWERTY layout mapping would
		actually be providing more identifying information for users in the UK than
		the actual mapping would (since most users in the UK do not use a US layout).

	<h3 id="incognito">Privacy Mode</h3>
	
	If a user agent provides an "incognito" or "privacy mode", then this API should
	act the same as it does outside of "privacy mode". The reason for this is that
	there is no universal neutral value that can be returned to ensure the user's
	privacy.
	
	User agents may choose to give the user the option to specify what value should
	be returned when in this mode, although care must be taken to ensure that the
	user does not get a false sense of security since this value would need to be
	updated when if they travel outside their home region.

<h2 id="acknowledgements-contributors">Acknowledgements</h2>

	Thanks to the following people for the discussions that lead
	to the creation of this proposal:

	Hadley Beeman (W3C TAG),
	Joe Downing (Google),
	Masayuki Nakano (Mozilla),
	Julien Wajsberg (Mozilla)

<h2 id="glossary">Glossary</h2>

: <dfn>scancode</dfn>
::	A value that the keyboard hardware assigns to each key so that it can be identified
	uniquely.
	See <a href="https://en.wikipedia.org/wiki/Scancode">https://en.wikipedia.org/wiki/Scancode</a>
	for additional information.
